const router = require('express').Router();
const Controller = require('../controller/data');

// 查询用户账单条目
router.get('/selectAll', async (req, res) => {

    const username = req.cookies.username;

    try {
        var data = await Controller.getAll(username);
        res.json({
            status: 200,
            message: '获取数据成功',
            data: data,
        });
    } catch (error) {
        console.log(error);
        res.json({
            status: 500,
            message: '获取数据失败',
            data: null,
        });
        return;
    }
})


/**{
                    id: '',
                    type: '选择类型',
                    date: '',
                    amount: '',
                    resume: '',
                    description: '',
                } */
// 添加用户账单条目
router.post('/addBill', async (req, res) => {
    const username = req.cookies.username;
    const { type, date, amount, resume, description } = req.body;

    try {
        var id = await Controller.addBill(username, type == '收入' ? 0 : 1, date, Number(amount)*100, resume, description, username);
        res.json({
            status: 200,
            message: '添加账单成功',
            id,
        });
    } catch (error) {
        console.log(error);
        res.json({
            status: 601,
            message: '添加账单失败',
            id: null,
        });
        return;
    }
})

// 删除用户账单条目
router.post('/deleteBills', async (req, res) => {
    const { id } = req.body;

    try {
        await Controller.deleteBills(id);
        res.json({
            status: 200,
            message: '删除账单成功',
        });
    } catch (error) {
        console.log(error);
        res.json({
            status: 602,
            message: '删除账单失败',
        });
        return;
    }
})

// 修改用户账单条目
router.post('/updateBill', async (req, res) => {
    const { _id, type, date, resume, description, amount } = req.body;
    try {
        await Controller.updateBill(_id, type == '收入' ? 0 : 1, date, Number(amount)*100, resume, description);
        res.json({
            status: 200,
            message: '修改账单成功',
        });
    } catch (error) {
        console.log(error);
        res.json({
            status: 603,
            message: '修改账单失败',
        });
        return;
    }
})

module.exports = router;
